<template>
	<view class="water-delivery-container">
		<view class="status-tabs">
			<view 
				v-for="(item, index) in statusTabs" 
				:key="index" 
				class="tab-item" 
				:class="{ active: currentTab === index }"
				@click="switchTab(index)"
			>
				{{ item.name }}
			</view>
		</view>
		
		<view class="delivery-list">
			<view v-if="loading" class="loading">
				<uni-load-more status="loading" :contentText="loadingText"></uni-load-more>
			</view>
			
			<view v-else-if="deliveryList.length === 0" class="empty-list">
				<image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
				<view class="empty-text">暂无送水记录</view>
			</view>
			
			<view v-else>
				<view 
					v-for="(item, index) in deliveryList" 
					:key="index" 
					class="delivery-item card"
					@click="goToDetail(item.service_id)"
				>
					<view class="item-header">
						<view class="product-name">{{ item.product_name }}</view>
						<view class="status" :class="getStatusClass(item.status)">{{ item.status }}</view>
					</view>
					
					<view class="item-info">
						<view class="info-row">
							<text class="label">数量:</text>
							<text class="value">{{ item.quantity }} × ¥{{ parseFloat(item.unit_price).toFixed(2) }}</text>
						</view>
						<view class="info-row">
							<text class="label">总金额:</text>
							<text class="value price">¥{{ parseFloat(item.total_amount).toFixed(2) }}</text>
						</view>
						<view class="info-row">
							<text class="label">期望送达:</text>
							<text class="value">{{ formatDate(item.expected_delivery_time) }}</text>
						</view>
						<view class="info-row">
							<text class="label">收货地址:</text>
							<text class="value address">{{ item.delivery_address }}</text>
						</view>
					</view>
					
					<view class="item-footer">
						<view class="time">申请时间: {{ formatDate(item.application_time) }}</view>
						<view class="actions">
							<button 
								v-if="item.status === '待受理' || item.status === '已确认备货中'" 
								class="btn cancel-btn"
								@click.stop="cancelDelivery(item.service_id)"
							>取消</button>
							<button 
								v-if="item.status === '已送达'" 
								class="btn rate-btn"
								@click.stop="goToRate(item.service_id)"
							>评价</button>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="fixed-bottom">
			<button class="submit-btn" @click="goToApply">申请送水</button>
		</view>
	</view>
</template>

<script>
	import { getCurrentUserWaterDeliveries, cancelWaterDelivery } from '@/api/services.js'
	import { request } from '@/api/request.js'
	
	export default {
		data() {
			return {
				statusTabs: [
					{ name: '全部', status: '' },
					{ name: '待受理', status: '待受理' },
					{ name: '处理中', status: ['已确认备货中', '配送中'] },
					{ name: '已完成', status: ['已送达', '已评价'] },
					{ name: '已取消', status: '已取消' }
				],
				currentTab: 0,
				deliveryList: [],
				loading: false,
				loadingText: {
					contentdown: '正在加载...',
					contentrefresh: '正在加载...',
					contentnomore: '没有更多数据了'
				}
			}
		},
		onLoad() {
			this.getDeliveryList()
		},
		methods: {
			// 切换状态标签
			switchTab(index) {
				this.currentTab = index
				this.getDeliveryList()
			},
			
			// 获取送水服务列表
			async getDeliveryList() {
				this.loading = true
				try {
					const params = {}
					const currentStatus = this.statusTabs[this.currentTab].status
					
					if (currentStatus) {
						if (Array.isArray(currentStatus)) {
							// 如果是数组，需要在后端处理多状态查询
							params.status = currentStatus.join(',')
						} else {
							params.status = currentStatus
						}
					}
					
					try {
						// 直接获取原始响应数据
						const rawResponse = await request({
							url: '/api/services/my-water-deliveries/',
							method: 'GET',
							data: params
						})
						
						console.log('送水服务列表原始数据:', JSON.stringify(rawResponse, null, 2))
						
						// 使用正常处理方式获取格式化后的数据
						const res = await getCurrentUserWaterDeliveries(params)
						console.log('格式化后的送水服务列表:', JSON.stringify(res, null, 2))
						
						this.deliveryList = res
					} catch (apiError) {
						console.error('API请求错误:', apiError)
						
						// 显示具体的错误信息
						let errorMsg = '获取数据失败'
						if (apiError.message) {
							errorMsg += ': ' + apiError.message
						}
						
						uni.showToast({
							title: errorMsg,
							icon: 'none',
							duration: 3000
						})
						
						this.deliveryList = []
					}
				} catch (error) {
					console.error('获取送水服务列表失败', error)
					
					uni.showToast({
						title: '获取数据时发生错误',
						icon: 'none',
						duration: 2000
					})
					
					this.deliveryList = []
				} finally {
					this.loading = false
				}
			},
			
			// 格式化日期
			formatDate(dateString) {
				if (!dateString) return ''
				const date = new Date(dateString)
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
			},
			
			// 获取状态对应的样式类
			getStatusClass(status) {
				switch (status) {
					case '待受理':
						return 'status-pending'
					case '已确认备货中':
					case '配送中':
						return 'status-processing'
					case '已送达':
					case '已评价':
						return 'status-completed'
					case '已取消':
						return 'status-cancelled'
					default:
						return ''
				}
			},
			
			// 跳转到详情页
			goToDetail(id) {
				uni.navigateTo({
					url: `/pages/services/water-delivery/detail?id=${id}`
				})
			},
			
			// 跳转到评价页
			goToRate(id) {
				uni.navigateTo({
					url: `/pages/services/water-delivery/rate?id=${id}`
				})
			},
			
			// 跳转到申请页
			goToApply() {
				uni.navigateTo({
					url: '/pages/services/water-delivery/apply'
				})
			},
			
			// 取消送水服务
			async cancelDelivery(id) {
				uni.showModal({
					title: '确认取消',
					content: '确定要取消此送水服务吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								await cancelWaterDelivery(id)
								uni.showToast({
									title: '取消成功',
									icon: 'success'
								})
								// 刷新列表
								this.getDeliveryList()
							} catch (error) {
								uni.showToast({
									title: '取消失败',
									icon: 'none'
								})
								console.error('取消送水服务失败', error)
							}
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.water-delivery-container {
		padding: 20rpx;
		padding-bottom: 120rpx;
		background-color: #F8F8F8;
		min-height: 100vh;
		
		.status-tabs {
			display: flex;
			background-color: #FFFFFF;
			border-radius: 12rpx;
			margin-bottom: 20rpx;
			overflow: hidden;
			box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
			
			.tab-item {
				flex: 1;
				text-align: center;
				padding: 20rpx 0;
				font-size: 28rpx;
				color: #666;
				position: relative;
				
				&.active {
					color: #2979ff;
					font-weight: bold;
					
					&:after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 50%;
						transform: translateX(-50%);
						width: 40rpx;
						height: 6rpx;
						background-color: #2979ff;
						border-radius: 3rpx;
					}
				}
			}
		}
		
		.delivery-list {
			.loading, .empty-list {
				padding: 60rpx 0;
				text-align: center;
			}
			
			.empty-image {
				width: 200rpx;
				height: 200rpx;
				margin-bottom: 20rpx;
			}
			
			.empty-text {
				color: #999;
				font-size: 28rpx;
			}
			
			.delivery-item {
				margin-bottom: 20rpx;
				
				.item-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 20rpx;
					
					.product-name {
						font-size: 32rpx;
						font-weight: bold;
					}
					
					.status {
						font-size: 24rpx;
						padding: 4rpx 16rpx;
						border-radius: 20rpx;
						
						&.status-pending {
							color: #ff9900;
							background-color: rgba(255, 153, 0, 0.1);
						}
						
						&.status-processing {
							color: #2979ff;
							background-color: rgba(41, 121, 255, 0.1);
						}
						
						&.status-completed {
							color: #19be6b;
							background-color: rgba(25, 190, 107, 0.1);
						}
						
						&.status-cancelled {
							color: #999;
							background-color: rgba(153, 153, 153, 0.1);
						}
					}
				}
				
				.item-info {
					background-color: #f9f9f9;
					border-radius: 8rpx;
					padding: 20rpx;
					margin-bottom: 20rpx;
					
					.info-row {
						display: flex;
						margin-bottom: 10rpx;
						
						&:last-child {
							margin-bottom: 0;
						}
						
						.label {
							width: 150rpx;
							color: #666;
							font-size: 26rpx;
						}
						
						.value {
							flex: 1;
							font-size: 26rpx;
							
							&.price {
								color: #ff5a5f;
								font-weight: bold;
							}
							
							&.address {
								word-break: break-all;
							}
						}
					}
				}
				
				.item-footer {
					display: flex;
					justify-content: space-between;
					align-items: center;
					
					.time {
						color: #999;
						font-size: 24rpx;
					}
					
					.actions {
						display: flex;
						
						.btn {
							font-size: 24rpx;
							padding: 6rpx 20rpx;
							border-radius: 30rpx;
							margin-left: 20rpx;
							
							&.cancel-btn {
								color: #666;
								border: 1rpx solid #ddd;
							}
							
							&.rate-btn {
								color: #2979ff;
								border: 1rpx solid #2979ff;
							}
						}
					}
				}
			}
		}
		
		.fixed-bottom {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: #fff;
			padding: 20rpx;
			box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
			
			.submit-btn {
				background-color: #2979ff;
				color: #fff;
				border-radius: 45rpx;
				font-size: 32rpx;
				height: 80rpx;
				line-height: 80rpx;
			}
		}
	}
</style> 